<template>
  <view class="detail-page">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <uni-load-more status="loading"></uni-load-more>
    </view>

    <!-- 用户详情内容 -->
    <view v-else-if="userInfo" class="content-container">
      <!-- 用户基本信息 -->
      <view class="info-section">
        <view class="section-title">
          <uni-icons type="person" size="16" color="#007aff"></uni-icons>
          <text class="title-text">用户信息</text>
          <view class="status-indicator">
            <view class="online-dot"></view>
            <text class="status-text">在线</text>
          </view>
        </view>
        <view class="info-content">
          <view class="info-row">
            <text class="info-label">用户名称：</text>
            <text class="info-value user-name">{{ userInfo.userName }}</text>
          </view>
          <view class="info-row" v-if="userInfo.deptName">
            <text class="info-label">所属部门：</text>
            <text class="info-value">{{ userInfo.deptName }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">登录时间：</text>
            <text class="info-value">{{ parseTime(userInfo.loginTime) }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">在线时长：</text>
            <text class="info-value duration-text">{{ getOnlineDuration(userInfo.loginTime) }}</text>
          </view>
        </view>
      </view>

      <!-- 会话信息 -->
      <view class="info-section">
        <view class="section-title">
          <uni-icons type="gear" size="16" color="#007aff"></uni-icons>
          <text class="title-text">会话信息</text>
        </view>
        <view class="info-content">
          <view class="info-row">
            <text class="info-label">会话编号：</text>
            <text class="info-value token-text">{{ userInfo.tokenId }}</text>
            <button class="copy-btn" size="mini" @click="handleCopy(userInfo.tokenId, 'Token')">
              <uni-icons type="copy" size="12"></uni-icons>
            </button>
          </view>
          <view class="info-row">
            <text class="info-label">会话状态：</text>
            <uni-tag text="活跃" type="success" size="small"></uni-tag>
          </view>
        </view>
      </view>

      <!-- 网络信息 -->
      <view class="info-section">
        <view class="section-title">
          <uni-icons type="globe" size="16" color="#007aff"></uni-icons>
          <text class="title-text">网络信息</text>
        </view>
        <view class="info-content">
          <view class="info-row">
            <text class="info-label">登录地址：</text>
            <text class="info-value ip-text">{{ userInfo.ipaddr }}</text>
            <button class="copy-btn" size="mini" @click="handleCopy(userInfo.ipaddr, 'IP地址')">
              <uni-icons type="copy" size="12"></uni-icons>
            </button>
          </view>
          <view class="info-row" v-if="userInfo.loginLocation">
            <text class="info-label">登录地点：</text>
            <text class="info-value">{{ userInfo.loginLocation }}</text>
          </view>
        </view>
      </view>

      <!-- 设备信息 -->
      <view class="info-section" v-if="userInfo.os || userInfo.browser">
        <view class="section-title">
          <uni-icons type="gear" size="16" color="#007aff"></uni-icons>
          <text class="title-text">设备信息</text>
        </view>
        <view class="info-content">
          <view class="info-row" v-if="userInfo.os">
            <text class="info-label">操作系统：</text>
            <text class="info-value">{{ userInfo.os }}</text>
          </view>
          <view class="info-row" v-if="userInfo.browser">
            <text class="info-label">浏览器：</text>
            <text class="info-value">{{ userInfo.browser }}</text>
          </view>
        </view>
      </view>

      <!-- 安全监控 -->
      <view class="info-section security-section">
        <view class="section-title">
          <uni-icons type="eye" size="16" color="#52c41a"></uni-icons>
          <text class="title-text">安全监控</text>
        </view>
        <view class="security-content">
          <view class="security-item">
            <view class="security-icon success">
              <uni-icons type="checkmarkempty" size="16" color="#52c41a"></uni-icons>
            </view>
            <view class="security-info">
              <text class="security-title">会话状态正常</text>
              <text class="security-desc">用户当前会话状态良好，无异常行为</text>
            </view>
          </view>
          <view class="security-item">
            <view class="security-icon info">
              <uni-icons type="info" size="16" color="#1890ff"></uni-icons>
            </view>
            <view class="security-info">
              <text class="security-title">登录位置监控</text>
              <text class="security-desc">建议关注异地登录情况</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 操作历史 -->
      <view class="info-section" v-if="recentActions.length > 0">
        <view class="section-title">
          <uni-icons type="list" size="16" color="#007aff"></uni-icons>
          <text class="title-text">最近操作</text>
        </view>
        <view class="actions-content">
          <view v-for="(action, index) in recentActions" :key="index" class="action-item">
            <view class="action-time">{{ parseTime(action.time, '{h}:{i}') }}</view>
            <view class="action-desc">{{ action.description }}</view>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-section">
        <view class="action-buttons">
          <button class="refresh-btn" type="default" @click="handleRefresh">
            <uni-icons type="refresh" size="16" color="#007aff"></uni-icons>
            刷新
          </button>
          <button class="logout-btn" type="primary" @click="handleForceLogout">
            <uni-icons type="close" size="16" color="#fff"></uni-icons>
            强退
          </button>
        </view>
      </view>
    </view>

    <!-- 错误状态 -->
    <view v-else class="error-container">
      <uni-icons type="info" size="40" color="#ccc"></uni-icons>
      <text class="error-text">用户已下线或会话不存在</text>
      <button class="retry-btn" @click="getUserDetail">重新加载</button>
    </view>
  </view>
</template>

<script setup>
import {getCurrentInstance, ref} from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import {forceLogout, list} from '@/api/monitor/online'
import {parseTime} from '@/utils/ruoyi'

const {proxy} = getCurrentInstance()

// 响应式数据
const userInfo = ref(null)
const loading = ref(true)
const tokenId = ref('')

// 模拟最近操作数据
const recentActions = ref([
  {time: new Date(Date.now() - 5 * 60 * 1000), description: '访问用户管理页面'},
  {time: new Date(Date.now() - 15 * 60 * 1000), description: '查看系统日志'},
  {time: new Date(Date.now() - 30 * 60 * 1000), description: '修改个人信息'}
])

// ==================== 修复：使用 onLoad 生命周期钩子 ====================
onLoad((options) => {
  if (options && options.tokenId) {
    tokenId.value = options.tokenId
    getUserDetail()
  } else {
    loading.value = false
    proxy.$modal.showToast('缺少Token参数')
  }
})

// 获取用户详情
async function getUserDetail() {
  loading.value = true

  try {
    // 通过列表接口查找指定用户
    const response = await list({})
    if (response.code === 200 && response.rows) {
      const user = response.rows.find(item => item.tokenId === tokenId.value)
      if (user) {
        userInfo.value = user
      } else {
        userInfo.value = null
        proxy.$modal.showToast('用户已下线')
      }
    } else {
      userInfo.value = null
      proxy.$modal.showToast('获取用户详情失败')
    }
  } catch (error) {
    console.error('获取用户详情失败:', error)
    userInfo.value = null
    proxy.$modal.showToast('获取用户详情失败')
  } finally {
    loading.value = false
  }
}

// 计算在线时长
function getOnlineDuration(loginTime) {
  if (!loginTime) return '未知'

  const now = new Date()
  const login = new Date(loginTime)
  const diff = now - login

  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))

  if (days > 0) {
    return `${days}天${hours}小时${minutes}分钟`
  } else if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else {
    return `${minutes}分钟`
  }
}

// 复制内容
function handleCopy(content, type) {
  uni.setClipboardData({
    data: content,
    success: () => {
      proxy.$modal.showToast(`${type}已复制到剪贴板`)
    },
    fail: () => {
      proxy.$modal.showToast('复制失败')
    }
  })
}

// 刷新状态
function handleRefresh() {
  getUserDetail()
  proxy.$modal.showToast('状态已刷新')
}

// 强制下线
async function handleForceLogout() {
  if (!userInfo.value) return

  const result = await proxy.$modal.confirm(`是否确认强制下线用户"${userInfo.value.userName}"？`)
  if (result) {
    try {
      const response = await forceLogout(userInfo.value.tokenId)
      if (response.code === 200) {
        proxy.$modal.showToast('强制下线成功')
        setTimeout(() => {
          handleBack()
        }, 1500)
      } else {
        proxy.$modal.showToast(response.msg || '强制下线失败')
      }
    } catch (error) {
      console.error('强制下线失败:', error)
      proxy.$modal.showToast('强制下线失败')
    }
  }
}

// 返回上一页
function handleBack() {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
@import '@/styles/detail-page.scss';

// 在线用户详情页面特定样式
.online-detail-page {
  // 可以添加在线用户特有的样式覆盖
}
</style>